#include "mainwindow.h"
#include <QApplication>
#include <QtCore>
#include <QtSql>
#include <QMessageBox>
#include <QInputDialog>


#define PIG_DIR ".PigBills"
#define PIG_DATABASE ".PigBills/bills.pig"


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QDir installDir(QDir::homePath());
    if(!installDir.exists(PIG_DIR)){
        installDir.mkdir(PIG_DIR);
    }

    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    QString dbPath=QDir::homePath();
    dbPath+="/";
    dbPath+=PIG_DATABASE;
    db.setDatabaseName(dbPath);

    if (!db.open()) {
        QMessageBox::warning(NULL, QObject::tr("Pig Bills"), QObject::tr("Cannot open Database!"));
    }

    QSqlQuery mq;
    if (!mq.exec("select * from pig_config")) {
        //Do installation;
        QFile fInstall(":/db/install.sql");
        fInstall.open(QIODevice::ReadOnly | QIODevice::Text);
        foreach(QString sql, fInstall.readAll().split(';')) {
            mq.exec(sql);
        }
        fInstall.close();

    }
    else {
        \
        mq.clear();
    }
    mq.prepare("select value from pig_config where name='PASSWORD'");
    mq.exec();
    if (mq.next()) {
        //Verify password;
        bool isOK;
        QString raw = QInputDialog::getText(NULL, QObject::tr("Pig Bills"), QObject::tr("Enter the password to visit data"), QLineEdit::Password, NULL, &isOK);
        if (isOK) {
            QByteArray rawPassword = QCryptographicHash::hash(raw.toUtf8(), QCryptographicHash::Md5);
            QString password = QString(rawPassword.toHex());
            if (password.compare(mq.value(0).toString()) != 0) {
                QMessageBox::warning(NULL, QObject::tr("Pig Bills"), QObject::tr("Wrong password, cannot visit data"));
                mq.clear();
                return 0;
            }
            mq.clear();
        }
        else {
            mq.clear();
            return 0;
        }
    }
    MainWindow w;
    w.show();

    a.setWindowIcon(QIcon(":/icon/logo.png"));

    return a.exec();
}
